package app.stock.tools;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

import app.common.DatabaseManager;
import app.common.GlobalConstants;
import app.common.PropertyUtil;

public class DatabaseBackup {
	private static String dir = "C:\\training\\project\\testjava\\backup\\db\\";
	private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

	public static void main(String[] args) {
		backupDatabase();
		// restoreDatabase();
	}

	private static String getDir() {
		return dir + sdf.format(new Date()) + "\\";
	}

	public static void backupDatabase() {
		Connection conn = null;
		CallableStatement cs = null;
		try {
			PropertyUtil.put(GlobalConstants.key_appMode, GlobalConstants.value_appMode_backup);
			GlobalConstants.listCurrent();
			// DatabaseManager.shutdownDB();
			DatabaseManager.init();
			conn = DatabaseManager.getConnection();
			cs = conn.prepareCall("CALL SYSCS_UTIL.SYSCS_BACKUP_DATABASE(?)");
			cs.setString(1, getDir());
			cs.execute();
			DatabaseManager.closeResource(null, cs, conn);
			System.out.println("Backup database successfuly");
			DatabaseManager.shutdownDB();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void restoreDatabase() {
		Connection conn = null;
		try {
			PropertyUtil.put(GlobalConstants.key_appMode, GlobalConstants.value_appMode_restore);
			GlobalConstants.listCurrent();
			// DatabaseManager.shutdownDB();
			String dbURL = DatabaseManager.getDatabaseUrl() + ";restoreFrom=" + getDir() + "\\data";
			Properties props = new Properties();
			conn = DriverManager.getConnection(dbURL, props);
			DatabaseManager.closeResource(null, null, conn);
			System.out.println("Restore database successfuly");
			DatabaseManager.shutdownDB();
		} catch (Exception e) {
			e.printStackTrace();
			DatabaseManager.closeResource(null, null, conn);
			DatabaseManager.shutdownDB();
		}
	}
}
